package leetcode.other.p92;

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummyNode = new ListNode(-1, head);
        ListNode p0 = dummyNode;
        // 遍历到left的前一个节点
        for (int i = 0; i < left - 1; i++) {
            p0 = p0.next;
        }
        ListNode cur = p0.next;
        ListNode pre = null;
        ListNode nxt = null;
        for (int i = 0; i < right - left + 1; i++) {
            nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        p0.next.next = cur;
        p0.next = pre;
        return dummyNode.next;
    }
}